package cn.lblbc.stopwatch

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.animation.ScaleAnimation
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    private lateinit var timerText: TextView
    private lateinit var startPauseButton: TextView
    private lateinit var resetLapButton: TextView
    private lateinit var noRecordsText: TextView
    private lateinit var lapRecyclerView: RecyclerView
    private lateinit var lapContainer: View
    
    private var isRunning = false
    private var startTime: Long = 0
    private var elapsedTime: Long = 0
    private var lapCount = 0
    private val lapRecords = mutableListOf<LapRecord>()
    private lateinit var lapAdapter: LapAdapter
    private var currentTheme = THEME_CLASSIC
    
    companion object {
        const val PREFS_NAME = "StopwatchPrefs"
        const val THEME_KEY = "SelectedTheme"
        const val THEME_CLASSIC = "classic"
        const val THEME_CYBERPUNK = "cyberpunk"
        const val THEME_OCEAN = "ocean"
        const val THEME_SUNSET = "sunset"
        const val THEME_FOREST = "forest"
        const val THEME_MINIMALIST = "minimalist"
        const val THEME_DEEPSPACE = "deepspace"
        const val THEME_CRT = "crt"
        const val THEME_CANDY = "candy"
        const val THEME_FIRE = "fire"
        
        val THEME_NAMES = arrayOf(
            "经典暗色", "赛博朋克", "海洋", "日落", "森林",
            "极简白色", "深空黑", "复古CRT", "粉彩糖果", "火焰"
        )
        
        val THEME_KEYS = arrayOf(
            THEME_CLASSIC, THEME_CYBERPUNK, THEME_OCEAN, THEME_SUNSET, THEME_FOREST,
            THEME_MINIMALIST, THEME_DEEPSPACE, THEME_CRT, THEME_CANDY, THEME_FIRE
        )
    }
    
    private val handler = Handler(Looper.getMainLooper())
    private val updateTimerRunnable = object : Runnable {
        override fun run() {
            if (isRunning) {
                val currentTime = System.currentTimeMillis()
                elapsedTime = currentTime - startTime
                updateTimerDisplay()
                handler.postDelayed(this, 10) // 更新频率10毫秒
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        // 应用保存的主题
        applySavedTheme()
        
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        initViews()
        setupClickListeners()
        setupRecyclerView()
        updateLapUI() // 初始化时更新UI状态
    }
    
    override fun onResume() {
        super.onResume()
        
        // 获取保存的主题
        val prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
        val savedTheme = prefs.getString(THEME_KEY, THEME_CLASSIC) ?: THEME_CLASSIC
        
        // 检查主题是否已更改
        if (savedTheme != currentTheme) {
            // 重新创建Activity以应用新主题
            recreate()
        }
    }
    
    private fun applySavedTheme() {
        val prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
        currentTheme = prefs.getString(THEME_KEY, THEME_CLASSIC) ?: THEME_CLASSIC
        
        when (currentTheme) {
            THEME_CLASSIC -> setTheme(R.style.Theme_Stopwatch_Classic)
            THEME_CYBERPUNK -> setTheme(R.style.Theme_Stopwatch_Cyberpunk)
            THEME_OCEAN -> setTheme(R.style.Theme_Stopwatch_Ocean)
            THEME_SUNSET -> setTheme(R.style.Theme_Stopwatch_Sunset)
            THEME_FOREST -> setTheme(R.style.Theme_Stopwatch_Forest)
            THEME_MINIMALIST -> setTheme(R.style.Theme_Stopwatch_Minimalist)
            THEME_DEEPSPACE -> setTheme(R.style.Theme_Stopwatch_DeepSpace)
            THEME_CRT -> setTheme(R.style.Theme_Stopwatch_CRT)
            THEME_CANDY -> setTheme(R.style.Theme_Stopwatch_Candy)
            THEME_FIRE -> setTheme(R.style.Theme_Stopwatch_Fire)
        }
    }
    
    private fun initViews() {
        timerText = findViewById(R.id.timerText)
        startPauseButton = findViewById(R.id.startPauseButton)
        resetLapButton = findViewById(R.id.resetLapButton)
        noRecordsText = findViewById(R.id.noRecordsText)
        lapRecyclerView = findViewById(R.id.lapRecyclerView)
        lapContainer = findViewById(R.id.lapContainer)
        
        // 找到并设置设置按钮的点击事件
        val settingsButton = findViewById<ImageView>(R.id.settings_button)
        settingsButton.setOnClickListener {
            val intent = Intent(this, SettingsActivity::class.java)
            startActivity(intent)
        }
    }
    
    private fun setupRecyclerView() {
        lapAdapter = LapAdapter(lapRecords)
        lapRecyclerView.adapter = lapAdapter
        lapRecyclerView.layoutManager = LinearLayoutManager(this)
    }
    
    private fun setupClickListeners() {
        // 开始/暂停按钮点击事件
        startPauseButton.setOnClickListener {
            animateButtonClick(startPauseButton)
            
            if (isRunning) {
                // 当前正在运行，需要暂停
                pauseTimer()
                updateControlButtons(false) // 显示开始和重置按钮
            } else {
                // 当前已暂停，需要开始
                startTimer()
                updateControlButtons(true) // 显示暂停和标志按钮
            }
        }
        
        // 重置/标志按钮点击事件
        resetLapButton.setOnClickListener {
            animateButtonClick(resetLapButton)
            
            if (isRunning) {
                // 运行状态下是标志按钮
                recordLap()
            } else {
                // 停止状态下是重置按钮
                resetTimer()
            }
        }
    }
    
    private fun startTimer() {
        isRunning = true
        startTime = System.currentTimeMillis() - elapsedTime
        handler.post(updateTimerRunnable)
    }
    
    private fun pauseTimer() {
        isRunning = false
        handler.removeCallbacks(updateTimerRunnable)
    }
    
    private fun resetTimer() {
        pauseTimer()
        elapsedTime = 0
        lapCount = 0
        lapRecords.clear()
        lapAdapter.notifyDataSetChanged()
        updateTimerDisplay()
        updateLapUI()
    }
    
    private fun recordLap() {
        lapCount++
        val lapTime = formatTime(elapsedTime)
        lapRecords.add(0, LapRecord(lapCount, lapTime)) // 添加到列表开头
        lapAdapter.notifyItemInserted(0)
        lapAdapter.notifyDataSetChanged()
        updateLapUI()
    }
    
    private fun updateTimerDisplay() {
        timerText.text = formatTime(elapsedTime)
    }
    
    private fun updateLapUI() {
        if (lapRecords.isEmpty()) {
            lapContainer.visibility = View.INVISIBLE
        } else {
            lapContainer.visibility = View.VISIBLE
            noRecordsText.visibility = View.GONE
            lapRecyclerView.visibility = View.VISIBLE
        }
    }
    
    private fun updateControlButtons(isRunning: Boolean) {
        if (isRunning) {
            startPauseButton.text = getString(R.string.pause)
            startPauseButton.background = getDrawable(R.drawable.circle_background_orange)
            resetLapButton.text = getString(R.string.lap)
            resetLapButton.background = getDrawable(R.drawable.circle_background)
            resetLapButton.setTextColor(getColor(R.color.white))
        } else {
            startPauseButton.text = getString(R.string.start)
            startPauseButton.background = getDrawable(R.drawable.circle_background)
            resetLapButton.text = getString(R.string.reset)
            resetLapButton.background = getDrawable(R.drawable.circle_background_gray)
            resetLapButton.setTextColor(getColor(R.color.text_light))
        }
    }
    
    private fun formatTime(elapsedMillis: Long): String {
        val minutes = (elapsedMillis / 1000) / 60
        val seconds = (elapsedMillis / 1000) % 60
        val milliseconds = (elapsedMillis % 1000) / 10 // 取前两位毫秒
        
        return String.format("%02d:%02d.%02d", minutes, seconds, milliseconds)
    }
    
    private fun animateButtonClick(view: View) {
        val scaleDown = ScaleAnimation(
            1f, 0.95f,
            1f, 0.95f,
            ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
            ScaleAnimation.RELATIVE_TO_SELF, 0.5f
        )
        scaleDown.duration = 100
        scaleDown.fillAfter = true
        
        val scaleUp = ScaleAnimation(
            0.95f, 1f,
            0.95f, 1f,
            ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
            ScaleAnimation.RELATIVE_TO_SELF, 0.5f
        )
        scaleUp.duration = 100
        scaleUp.fillAfter = true
        scaleUp.startOffset = 100
        
        view.startAnimation(scaleDown)
        view.startAnimation(scaleUp)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(updateTimerRunnable)
    }
}